package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.spzx.manager.service.VerificationCodeService;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: VerificationCodeServiceImpl
 * @Package: com.atguigu.spzx.manager.service.impl
 * @Description
 * @Author 孤妤
 * @Date: 2023/12/3 17:18
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public ValidateCodeVo getValidateCode() {
        // 使用hutool工具包中的工具类生成图片验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        String code = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();
        // UUID生成key存储验证码
        String codeKey = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("user:code:"+codeKey,code,5, TimeUnit.MINUTES);
        // 创建返回给前端的验证码对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(codeKey);
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);
        return validateCodeVo;
    }
}
